package com.xbongbong.lfasr.event;

import com.alibaba.fastjson.JSON;
import com.xbongbong.lfasr.client.LfasrClientImp;
import com.xbongbong.lfasr.exception.LfasrException;
import com.xbongbong.lfasr.file.LocalPersistenceFile;
import com.xbongbong.lfasr.model.EventType;
import com.xbongbong.lfasr.model.Message;
import com.xbongbong.lfasr.model.UploadParams;
import com.xbongbong.lfasr.worker.HttpWorker;
import com.xbongbong.paas.toolbox.util.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EventHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(EventHandler.class);
    private UploadParams upParams;
    private long file_piece_size;
    private boolean is_resume = false;
    private EventQueue<Event> queue;
    private HashMap<String, Boolean> slice_hm = new HashMap();
    private CountDownLatch latch = new CountDownLatch(1);
    private ExecutorService exec;
    private int threadNum = 10;

    public EventHandler(UploadParams upParams, long file_piece_size, boolean is_resume) {
        this.upParams = upParams;
        this.file_piece_size = file_piece_size;
        this.is_resume = is_resume;
        this.queue = new EventQueue();
        this.exec = Executors.newFixedThreadPool(this.threadNum,new NamedThreadFactory("xbb-EventHandler-Executor"));
        this.start();
    }

    public void start() {
        for(int i = 0; i < this.threadNum; ++i) {
            this.exec.execute(new ProcessorThread(this));
        }

    }

    public void addEvent(Event event) {
        try {
            this.queue.put(event);
        } catch (InterruptedException var3) {
            var3.printStackTrace();
            // 恢复中断状态
            Thread.currentThread().interrupt();
        }

    }

    public void modifySliceHM(String slice_id, boolean bool) {
        this.slice_hm.put(slice_id, bool);
    }

    public boolean isSendAll() {
        boolean isSend = true;
        if (this.slice_hm == null) {
            return isSend;
        } else {
            int sendNum = 0;
            Iterator iter = this.slice_hm.entrySet().iterator();

            while(iter.hasNext()) {
                Entry entry = (Entry)iter.next();
                if ("false".equalsIgnoreCase(entry.getValue().toString())) {
                    isSend = false;
                } else {
                    ++sendNum;
                }
            }

            LOGGER.info(String.format("[COMPENT]-%s [PROCESS]-%s [ID]-%s [STATUS]-%s [MEASURE]-%s [DEF]-%s", "CLIENT", "EventHandler", "", "", "(-1) ms", "upload file " + sendNum + "/" + this.slice_hm.size()));
            return isSend;
        }
    }

    public void await() throws InterruptedException {
        this.latch.await();
    }

    public void shutdownNow() {
        this.exec.shutdownNow();
    }

    public class ProcessorThread implements Runnable {

        private EventHandler eventHandler;

        public ProcessorThread(EventHandler var1) {
            this.eventHandler = var1;
        }

        @Override
        public void run() {
            while (true) {
                Event event = null;

                try {
                    event = (Event) this.eventHandler.queue.take();
                } catch (InterruptedException var11) {
                    // 恢复中断状态
                    Thread.currentThread().interrupt();
                    return;
                }

                HttpWorker worker;
                String result;
                if (event.getType().getValue() == EventType.LFASR_FILE_DATA_CONTENT.getValue()) {
                    worker = new HttpWorker();
                    result = worker.handle(event);
                    String slice_id = event.getFileSlice().getSliceID();
                    Message responseObj = null;

                    try {
                        responseObj = (Message) JSON.parseObject(result, Message.class);
                    } catch (Exception var8) {
                        EventHandler.LOGGER.warn(String.format("[COMPENT]-%s [PROCESS]-%s [ID]-%s [STATUS]-%s [MEASURE]-%s [DEF]-%s", "CLIENT", "EventHandler", event.getParams().getTaskId(), "", "(-1) ms", "slice_id:" + slice_id + " send fail...try again..."));
                        eventHandler.addEvent(event);
                        continue;
                    }

                    if (responseObj.getOk() == 0) {
                        try {
                            LocalPersistenceFile.writeNIO(LfasrClientImp.SERV_STORE_PATH_VAL + "/" + this.eventHandler.upParams.getTaskId() + ".dat", slice_id);
                            eventHandler.modifySliceHM(slice_id, true);
                        } catch (LfasrException var7) {
                            EventHandler.LOGGER.error(String.format("[COMPENT]-%s [PROCESS]-%s [ID]-%s [STATUS]-%s [MEASURE]-%s [DEF]-%s", "CLIENT", "EventHandler", event.getParams().getTaskId(), "", "(-1) ms", "write meta info to " + LfasrClientImp.SERV_STORE_PATH_VAL + "/" + this.eventHandler.upParams.getTaskId() + ".dat" + " error"), var7);
                        }

                        EventHandler.LOGGER.debug(String.format("[COMPENT]-%s [PROCESS]-%s [ID]-%s [STATUS]-%s [MEASURE]-%s [DEF]-%s", "CLIENT", "EventHandler", event.getParams().getTaskId(), "", "(-1) ms", "upload slice send success.file:" + this.eventHandler.upParams.getFile().getAbsolutePath() + ", slice_id:" + slice_id));
                    } else {
                        eventHandler.addEvent(event);
                        EventHandler.LOGGER.warn(String.format("[COMPENT]-%s [PROCESS]-%s [ID]-%s [STATUS]-%s [MEASURE]-%s [DEF]-%s", "CLIENT", "EventHandler", event.getParams().getTaskId(), "", "(-1) ms", "slice_id:" + slice_id + " send fail...try again..."));
                    }
                } else {
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException ignore) {
                        // 恢复中断状态
                        Thread.currentThread().interrupt();
                    }

                    worker = new HttpWorker();
                    result = worker.meger(event);
                    Message responseObj = null;

                    try {
                        responseObj = (Message) JSON.parseObject(result, Message.class);
                    } catch (Exception var9) {
                        eventHandler.addEvent(event);
                        EventHandler.LOGGER.warn(String.format("[COMPENT]-%s [PROCESS]-%s [ID]-%s [STATUS]-%s [MEASURE]-%s [DEF]-%s", "CLIENT", "EventHandler", event.getParams().getTaskId(), "", "(-1) ms", "send meger fail...try again...."));
                        continue;
                    }

                    if (responseObj.getOk() == 0) {
                        LocalPersistenceFile.deleteFile(new File(LfasrClientImp.SERV_STORE_PATH_VAL + "/" + this.eventHandler.upParams.getTaskId() + ".dat"));
                        EventHandler.LOGGER.info(String.format("[COMPENT]-%s [PROCESS]-%s [ID]-%s [STATUS]-%s [MEASURE]-%s [DEF]-%s", "CLIENT", "EventHandler", event.getParams().getTaskId(), "", "(-1) ms", "send meger success"));
                        this.eventHandler.latch.countDown();
                        return;
                    }

                    eventHandler.addEvent(event);
                    EventHandler.LOGGER.warn(String.format("[COMPENT]-%s [PROCESS]-%s [ID]-%s [STATUS]-%s [MEASURE]-%s [DEF]-%s", "CLIENT", "EventHandler", event.getParams().getTaskId(), "", "(-1) ms", "send meger fail...try again...."));
                }
            }
        }
    }
}
